/*
** main.c for colle in /home/butigi_b//colle
** 
** Made by boris butigieg
** Login   <butigi_b@epitech.net>
** 
** Started on  Mon Apr 18 19:18:37 2011 boris butigieg
** Last update Mon Apr 18 22:47:36 2011 james deubelbeiss
*/

#include <stdlib.h>
#include "my_mastermind.h"

void	my_mm_play(t_args *args)
{
  char		*buf;
  int		ret;
  int		i;

  buf = xmalloc(sizeof(*buf) * (args->slots + 3));
  i = 1;
  ret = 0;
  while (i <= args->tentatives)
    {
      if (ret == 0)
	{
	  my_putstr("--\nRound ");
	  my_putnbr(i);
	  my_putstr("\n");
	}
      if ((ret = my_mm_tour(args, i, buf)) == 1)
	i = args->tentatives + 1;
      else if (ret == 0)
	i++;
    }
  free(buf);
  if (ret == 1)
    my_putstr("win\n");
  else
    my_putstr("fail\n");
}

int	my_mm_tour(t_args *args, int tour, char *buf)
{
  int	size;

  my_putstr(">");
  size = read(0, buf, args->slots + 2);
  buf[args->slots] = '\0';
  if (size == -1)
    my_puterr("Read error\n");
  else if (size == args->slots + 2 || size < args->slots
	   || buf[args->slots - 1] == '\n')
    my_putstr("Code trop court/long\n");
  else if (!my_check_str_base(buf, args->pions))
    my_putstr("Tu fais nawak\n");
  else if (!my_strcmp(buf, args->code))
    return (1);
  else
    {
      my_putstr("Pions bien places : ");
      my_putnbr(my_mm_good(buf, args->code));
      my_putstr("\nPions mal places : ");
      my_putnbr(my_mm_bad(buf, args->code));
      my_putstr("\n");
      return (0);
    }
  return (-1);
}

int	my_mm_good(char *str, char *code)
{
  int	cpt;
  int	i;

  cpt = 0;
  i = 0;
  while (str[i] && code[i])
    {
      if (str[i] == code[i])
	cpt++;
      i++;
    }
  return (cpt);
}

int	my_mm_bad(char *str, char *code)
{
  int	cpt;
  int	i;
  int	j;

  cpt = 0;
  i = 0;
  while (str[i])
    {
      j = 0;
      while (code[j])
	{
	  if (str[i] == code[j])
	    {
	      cpt++;
	      while (code[j + 1])
		j++;
	    }
	  j++;
	}
      i++;
    }
  return (cpt - my_mm_good(str, code));
}
